<template>
  <div id="app">
    <div id="up_div">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="150px">
          <el-form-item label="采购订单号" prop="poCode">
            <el-input
              v-model="queryParams.poCode"
              placeholder="请输入采购订单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="采购申请单号" prop="prCode">
            <el-input
              v-model="queryParams.prCode"
              placeholder="请输入采购申请单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-input
              v-model="queryParams.supplierId"
              placeholder="请输入供应商"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="供应商编码" prop="supplierCode">
            <el-input
              v-model="queryParams.supplierCode"
              placeholder="请输入供应商编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="订单创建日期">
            <el-date-picker
              v-model="daterangeOrderDate"
              style="width: 240px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div id="down_div">
      <div class="app-container">
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:pmsPurchaseOrders:edit']"
            >修改</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:pmsPurchaseOrders:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="pmsPurchaseOrdersList" @selection-change="handleSelectionChange" :row-class-name="setRowClassName" >
          <el-table-column type="selection" width="55" align="center" />


          <el-table-column type="expand" >
            <template #default="props">
              <h3>商品明细</h3>
              <el-divider></el-divider>
              <el-table :data="props.row.pmsPurchaseRequisitionsDetails" border>
                <el-table-column
                  prop="productName"
                  label="商品名称"
                  width="180">
                </el-table-column>
                <el-table-column label="商品编码" align="center" prop="productCode" />
                <el-table-column label="sku编码" align="center" prop="skuCode" />
                <el-table-column label="规格型号" align="center" prop="productSpec" />
                <el-table-column label="单位" align="center" prop="productUnit" >
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit">
                    </dict-tag>
                  </template>
                </el-table-column>
                <el-table-column label="采购单价" align="center" prop="purchasePrice" />
                <el-table-column label="商品数量" align="center" prop="totalQuantity" />
                <el-table-column label="商品总价" align="center" prop="totalAmount" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="采购订单号" align="center" prop="poCode" width="150"/>
          <el-table-column label="采购申请单号" align="center" prop="prCode" width="150"/>
          <el-table-column label="供应商" align="center" prop="supplierId" width="180">
            <template slot-scope="scope">
              {{ getSelectLabel(supplierSelect,scope.row.supplierId) }}
            </template>
          </el-table-column>
          <el-table-column label="预计交货日期" align="center" prop="expectedDeliveryDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.expectedDeliveryDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="付款条款" align="center" prop="paymentTerms" />-->
          <el-table-column label="订单不含税总金额" align="center" prop="totalAmount"  width="150"/>
<!--          <el-table-column label="订单总税额" align="center" prop="totalTax"  width="150"/>-->
<!--          <el-table-column label="订单含税总金额" align="center" prop="totalAmountWithTax"  width="150"/>-->
          <el-table-column label="订单状态" align="center" prop="status" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pms_purchase_orders_status" :value="scope.row.status"/>
            </template>
          </el-table-column>receivingTime
          <el-table-column label="创建人" align="center" prop="createNickName" />
          <el-table-column label="订单创建日期" align="center" prop="orderDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购员" align="center" prop="purchaseNickName" />
          <el-table-column label="收货日期" align="center" prop="receivingTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.receivingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="审批通过时间" align="center" prop="approvedAt" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.approvedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>-->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                :disabled = "scope.row.status !== '1'"
                v-hasPermi="['system:pmsPurchaseOrders:edit']"
              >修改</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-truck"
                @click="receiving(scope.row)"
                :disabled = "scope.row.status !== '2'"
                v-hasPermi="['system:pmsPurchaseOrders:receive']"
              >收货</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-box"
                @click="inbound(scope.row)"
                :disabled = "scope.row.status !== '3'"
                v-hasPermi="['system:pmsPurchaseOrders:receive']"
              >待入库</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-back"
                @click="returnGoods(scope.row)"
                :disabled = "scope.row.status !== '3'"
                v-hasPermi="['system:pmsPurchaseOrders:receive']"
              >退货</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { listPmsPurchaseOrders, getPmsPurchaseOrders, delPmsPurchaseOrders, addPmsPurchaseOrders, updatePmsPurchaseOrders } from "@/api/system/pmsPurchaseOrders";
import {getPmsPurchaseRequisitions} from "@/api/system/pmsPurchaseRequisitions";
import {getSupplierSelect} from "@/api/system/selectVo";

export default {
  name: "PmsPurchaseOrders",
  dicts: ['pms_purchase_orders_status', 'pms_purchase_requisitions_priority','wms_product_unit'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单主，记录采购订单核心信息表格数据
      pmsPurchaseOrdersList: [],
      supplierSelect:[],
      // 弹出层标题
      title: "",
      // 最后更新时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        poCode: undefined,
        prId: undefined,
        prCode: undefined,
        supplierId: undefined,
        supplierCode: undefined,
        orderDate: undefined,
        expectedDeliveryDate: undefined,
        paymentTerms: undefined,
        totalAmount: undefined,
        totalTax: undefined,
        totalAmountWithTax: undefined,
        status: undefined,
        approverId: undefined,
        approvedAt: undefined,
        createdBy: undefined,
        createdAt: undefined,
        updatedAt: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        poId: [
          { required: true, message: "采购订单主键ID不能为空", trigger: "blur" }
        ],
        poCode: [
          { required: true, message: "采购订单编号不能为空", trigger: "blur" }
        ],
        prId: [
          { required: true, message: "采购申请单ID不能为空", trigger: "blur" }
        ],
        prCode: [
          { required: true, message: "采购申请单编号不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        supplierCode: [
          { required: true, message: "供应商编码不能为空", trigger: "blur" }
        ],
        orderDate: [
          { required: true, message: "订单创建日期不能为空", trigger: "blur" }
        ],
        expectedDeliveryDate: [
          { required: true, message: "预计交货日期不能为空", trigger: "blur" }
        ],
        paymentTerms: [
          { required: true, message: "付款条款不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "订单不含税总金额不能为空", trigger: "blur" }
        ],
        totalTax: [
          { required: true, message: "订单总税额不能为空", trigger: "blur" }
        ],
        totalAmountWithTax: [
          { required: true, message: "订单含税总金额不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        approverId: [
          { required: true, message: "审批人ID不能为空", trigger: "blur" }
        ],
        approvedAt: [
          { required: true, message: "审批通过时间不能为空", trigger: "blur" }
        ],
        createdBy: [
          { required: true, message: "创建人ID不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedAt: [
          { required: true, message: "最后更新时间不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getList();
    this.getSelect();
  },
  methods: {
    // 计算行样式
    setRowClassName({ row }) {
      if (row.receivingTime) {
        return 'row-received'; // 已收货（绿色）
      }

      if (!row.expectedDeliveryDate) return ''; // 如果无预计交货日期，不设置样式

      const expectedDate = new Date(row.expectedDeliveryDate);
      const currentDate = new Date();
      const diffDays = Math.floor((expectedDate - currentDate) / (1000 * 60 * 60 * 24));

      if (diffDays < 0) {
        return 'row-delayed'; // 延期（红色）
      } else if (diffDays <= 7) {
        return 'row-near-due'; // 临近7天内（黄色）
      }
      return ''; // 正常（无样式）
    },
    /** 查询采购订单主，记录采购订单核心信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderDate && '' != this.daterangeOrderDate) {
        this.queryParams.params["beginOrderDate"] = this.daterangeOrderDate[0];
        this.queryParams.params["endOrderDate"] = this.daterangeOrderDate[1];
      }
      listPmsPurchaseOrders(this.queryParams).then(response => {
        this.pmsPurchaseOrdersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        poId: undefined,
        poCode: undefined,
        prId: undefined,
        prCode: undefined,
        supplierId: undefined,
        supplierCode: undefined,
        orderDate: undefined,
        expectedDeliveryDate: undefined,
        paymentTerms: undefined,
        totalAmount: undefined,
        totalTax: undefined,
        totalAmountWithTax: undefined,
        status: undefined,
        approverId: undefined,
        approvedAt: undefined,
        createdBy: undefined,
        createdAt: undefined,
        updatedAt: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.poId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getPmsPurchaseRequisitions(row.prId).then(response => {
        row.deptName=response.data.deptName;
        row.nickName=response.data.nickName;
        row.priority=response.data.priority;
        row.requiredDate=response.data.requiredDate;
        row.remark=response.data.remark;
        row.totalQuantity=response.data.totalQuantity;
        this.$emit("edit", row);
      })
    },
    /** 收货按钮操作 */
    receiving(row) {
      getPmsPurchaseRequisitions(row.prId).then(response => {
        row.deptName=response.data.deptName;
        row.nickName=response.data.nickName;
        row.priority=response.data.priority;
        row.requiredDate=response.data.requiredDate;
        row.remark=response.data.remark;
        row.totalQuantity=response.data.totalQuantity;
        this.$emit("receiving", row);
      })
    },
    /** t退货按钮操作 */
    returnGoods(row) {
      getPmsPurchaseRequisitions(row.prId).then(response => {
        row.deptName=response.data.deptName;
        row.nickName=response.data.nickName;
        row.priority=response.data.priority;
        row.requiredDate=response.data.requiredDate;
        row.remark=response.data.remark;
        row.totalQuantity=response.data.totalQuantity;
        this.$emit("returnGoods", row);
      })
    },
    /** 入库按钮操作 */
    inbound(row) {
      getPmsPurchaseRequisitions(row.prId).then(response => {
        row.deptName=response.data.deptName;
        row.nickName=response.data.nickName;
        row.priority=response.data.priority;
        row.requiredDate=response.data.requiredDate;
        row.remark=response.data.remark;
        row.totalQuantity=response.data.totalQuantity;
        this.$emit("inbound", row);
      })
    },
    getSelect() {
      getSupplierSelect().then(response => {
        this.supplierSelect = response.data
      });
    },
    getSelectLabel(selectList, id) {
      if (!selectList || !id) return '-'
      const item = selectList.find(i => i.value === id)
      return item ? item.label : (id || '-')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.poId != null) {
            updatePmsPurchaseOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPmsPurchaseOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/pmsPurchaseOrders/export', {
        ...this.queryParams
      }, `pmsPurchaseOrders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
body, html {
  margin: 0;
  padding: 0;
  height: 100%;
}

#app {
//background-color: #f4f4f4;
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 3px;
}

#up_div {
  background-color: white;
  height: 30%;
  width: 100%;
  margin-bottom: 20px; /* Space between the two divs */
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px; /* Optional rounded corners */
}

#down_div {
  background-color: white;
  height: 70%;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px; /* Optional rounded corners */
}

/* 可根据需要调整打印区样式 */
.print-header h2 {
  font-weight: bold;
}

.print-footer p {
  margin: 4px 0;
}

/* 已收货（绿色背景） */
.el-table .row-received {
  background-color: #f0fff0 !important; /* 浅绿色 */
}

/* 延期（红色背景） */
.el-table .row-delayed {
  background-color: #fff0f0 !important; /* 浅红色 */
}

/* 临近7天（黄色背景） */
.el-table .row-near-due {
  background-color: #fff8e6 !important; /* 浅黄色 */
}

/* 覆盖斑马纹样式（如果需要） */
.el-table .row-received.el-table__row--striped {
  background-color: #e6ffe6 !important;
}
.el-table .row-delayed.el-table__row--striped {
  background-color: #ffe6e6 !important;
}
.el-table .row-near-due.el-table__row--striped {
  background-color: #fff2cc !important;
}
</style>
